﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Media;
using GameLogic.Controls;

namespace GameLogic.Logic
{
    // Finds the IGame which contains a given FrameworkElement and it's attached Behavior
    public class GameContainerFinder
    { 
        private GameContainer gameContainer;
        public event EventHandler OnGameContainerLoaded;

        public GameContainer GameContainer
        {
            get { return this.gameContainer; }
        }

        public GameContainerFinder(FrameworkElement contextElement)
        {
            if (contextElement.Parent != null 
                || Application.Current.RootVisual != null && Application.Current.RootVisual.Equals(contextElement))
            {
                this.FindGameContainer(contextElement);
            }
            else
            {
                contextElement.Loaded += this.OnContextElementLoaded;
            }
        }

        private void OnContextElementLoaded(object sender, RoutedEventArgs e)
        {
            this.FindGameContainer((FrameworkElement)sender);
        }

        private void FindGameContainer(FrameworkElement contextElement)
        {
            FrameworkElement parent = contextElement;
            while (parent != null)
            {
                if (typeof(GameContainer).IsAssignableFrom(parent.GetType()))
                {
                    this.gameContainer = parent as GameContainer;

                    if (this.OnGameContainerLoaded != null)
                    {
                        this.OnGameContainerLoaded(this, EventArgs.Empty);
                    }
                    break;
                }
                parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
            }
        }
    }
}
